package com.atguigu.yygh.user.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.helper.JwtHelper;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ybl
 * @version 1.9
 * @date 2021/5/20 11:32
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

  @Autowired
  private RedisTemplate<String, String> redisTemplate;

  @Autowired
  private PatientService patientService;

  // 用户登录验证
  @Override
  public Map<String, Object> login(LoginVo loginVo) {
    String phone = loginVo.getPhone();
    String code = loginVo.getCode();
    // 校验参数
    if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
      throw new YyghException(ResultCodeEnum.PARAM_ERROR);
    }

    // TODO 校验验证码
    //校验校验验证码
    String mobleCode = redisTemplate.opsForValue().get(phone);
    if (!code.equals(mobleCode)) {
      throw new YyghException(ResultCodeEnum.CODE_ERROR);
    }

    //绑定手机号码
    UserInfo userinfo = null;
    if (!StringUtils.isEmpty(loginVo.getOpenid())) {
      userinfo = this.getByOpenid(loginVo.getOpenid());
      if (null != userinfo) {
        userinfo.setPhone(loginVo.getPhone());
        this.updateById(userinfo);
      } else {
        throw new YyghException(ResultCodeEnum.DATA_ERROR);
      }
    }

    if (null == userinfo) {
      // 查看数据库是否有此
      userinfo = baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("phone", phone));
      if (null == userinfo) {
        userinfo = new UserInfo();
        userinfo.setStatus(1);
        userinfo.setPhone(phone);
        userinfo.setCreateTime(new Date());
        userinfo.setName("");
        baseMapper.insert(userinfo);
      }
    }

// 校验用户是否被禁用
    if (userinfo.getStatus() == 0) {
      throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
    }

    // 返回页面显示的信息
    Map<String, Object> map = new HashMap<>();
    String name = userinfo.getName();

    if (StringUtils.isEmpty(name)) {
      name = userinfo.getNickName();
    }
    if (StringUtils.isEmpty(name)) {
      name = userinfo.getPhone();
    }
    // TODO  生成token 记录登录
    String token = JwtHelper.createToken(userinfo.getId(), name);
    map.put("name", name);
    map.put("token", token);

    return map;
  }

  // 先根据openid进行数据库查询
  @Override
  public UserInfo getByOpenid(String openId) {
    UserInfo openid = baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("openid", openId));
    return openid;
  }

  /**
   * 用户认证
   *
   * @param id
   * @param userAuthVo
   */
  @Override
  public void userAuth(Long id, UserAuthVo userAuthVo) {
    UserInfo userInfo = baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("id", id));

    //设置认证信息
    //认证人姓名
    userInfo.setName(userAuthVo.getName());
    //其他认证信息
    userInfo.setCertificatesType(userAuthVo.getCertificatesType());
    userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
    userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
    userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
    baseMapper.updateById(userInfo);
  }

  //分页获取用户列表
  @Override
  public IPage<UserInfo> getUserInfoList(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
    // 如果查询条件不为空
    if (userInfoQueryVo != null) {
      //UserInfoQueryVo获取条件值
      String name = userInfoQueryVo.getKeyword(); //用户名称
      Integer status = userInfoQueryVo.getStatus();//用户状态
      Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
      String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
      String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间
      //对条件值进行非空判断
      QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
      if(!StringUtils.isEmpty(name)) {
        wrapper.like("name",name);
      }
      if(!StringUtils.isEmpty(status)) {
        wrapper.eq("status",status);
      }
      if(!StringUtils.isEmpty(authStatus)) {
        wrapper.eq("auth_status",authStatus);
      }
      if(!StringUtils.isEmpty(createTimeBegin)) {
        wrapper.ge("create_time",createTimeBegin);
      }
      if(!StringUtils.isEmpty(createTimeEnd)) {
        wrapper.le("create_time",createTimeEnd);
      }

      //调用mapper的方法
      IPage<UserInfo> pages = baseMapper.selectPage(pageParam, wrapper);

      //编号变成对应值封装
      pages.getRecords().forEach(this::packageUserInfo);

      return pages;
    }

    return baseMapper.selectPage(pageParam, null);
  }

  // 用户的锁定与解锁 0：锁定 1：正常
  @Override
  public void userLock(Long userId, Integer status) {
    if (status == 0 || status == 1) {
      UserInfo userInfo = new UserInfo();
      userInfo.setStatus(status);
      userInfo.setId(userId);
      baseMapper.updateById(userInfo);
    }
  }

  // 用户的详情
  @Override
  public Map<String, Object> userDetail(Long userId) {
    Map<String ,Object> map = new HashMap<>();
    UserInfo userInfo = baseMapper.selectById(userId);
    // 封装用户信息
    packageUserInfo(userInfo);
    map.put("userInfo",userInfo);
    // 添加就诊人信息
    map.put("patientList",patientService.findAll(userId));
    return map;
  }

  //认证审批
  @Override
  public void approval(Long userId, Integer authStatus) {
    if (authStatus == 2 || authStatus == -1){
      UserInfo userInfo = new UserInfo();
      userInfo.setAuthStatus(authStatus);
      userInfo.setId(userId);
      baseMapper.updateById(userInfo);
    }
  }

  // 封装用户信息 把数字封装为
  private void packageUserInfo(UserInfo userInfo) {
    //处理认证状态编码
    userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
    //处理用户状态 0  1
    String statusString = userInfo.getStatus().intValue() == 0 ? "锁定" : "正常";
    userInfo.getParam().put("statusString",statusString);
  }
}
